package com.szgr.baoyin.fragment;

import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ZoomControls;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
//import com.baidu.mapapi.overlayutil.PoiOverlay;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.szgr.baoyin.R;
import com.szgr.baoyin.activity.ChooseCityActivity;
import com.szgr.baoyin.activity.OrderActivity;
import com.szgr.baoyin.adapter.StationExpandableListAdapter;
import com.szgr.baoyin.adapter.StationListAdapter;

/**
 * 服务站
 * Created by Jimbo on 2015/9/16.
 */
public class ServiceStationFragment extends Fragment implements AdapterView.OnItemClickListener, OnGetPoiSearchResultListener, BaiduMap.OnMapTouchListener, View.OnClickListener {

    private MapView stationMapView;
    private ExpandableListView stationListView;
    private PoiSearch mPoiSearch;
    private BaiduMap baiduMap;
    private LocationClient mLocationClient;
    private boolean isMapMove = false;
    private BDLocationListener bdLocationListener;

    public ServiceStationFragment(){}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View ret = inflater.inflate(R.layout.fragment_service_station,container,false);
        initView(ret);
        return ret;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stationMapView.onDestroy();
        mLocationClient.stop();
        baiduMap = null;
    }

    @Override
    public void onResume() {
        super.onResume();
        stationMapView.onResume();
        mLocationClient.start();
    }

    @Override
    public void onPause() {
        super.onPause();
        stationMapView.onPause();
    }

    private void initView(View ret) {
        stationMapView = (MapView) ret.findViewById(R.id.service_station_map_view);
        baiduMap = stationMapView.getMap();
        //显示比例尺？
        stationMapView.showScaleControl(false);
        //显示放大缩小按钮？
        stationMapView.showZoomControls(false);
        //显示Logo？
        View logoView = stationMapView.getChildAt(1);
        if(logoView != null && (logoView instanceof ImageView || logoView instanceof ZoomControls)){
            logoView.setVisibility(View.INVISIBLE);
        }

        stationListView = (ExpandableListView) ret.findViewById(R.id.service_station_list_view);
        StationExpandableListAdapter listViewAdapter = new StationExpandableListAdapter(getActivity());
        stationListView.setAdapter(listViewAdapter);
        stationListView.setGroupIndicator(null);
        stationListView.setOnItemClickListener(this);

        //poi检索初始化变量
        mPoiSearch = PoiSearch.newInstance();
        mPoiSearch.setOnGetPoiSearchResultListener(this);

        //定位
        mLocationClient = new LocationClient(getActivity());
        initLocation();
        bdLocationListener = new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                System.out.println("--------->" + bdLocation.getLatitude() + ";" + bdLocation.getLongitude());
                if (baiduMap != null) {
                    locationCurrentSite(bdLocation);
                    doSearch(bdLocation.getLatitude(), bdLocation.getLongitude());
                }
            }
        };
        mLocationClient.registerLocationListener(bdLocationListener);

        baiduMap.setOnMapTouchListener(this);

        TextView tv_city = (TextView) ret.findViewById(R.id.current_city);
        tv_city.setOnClickListener(this);
    }

    /**
     * 定位当前地位置
     * @param bdLocation
     */
    private void locationCurrentSite(BDLocation bdLocation) {
        baiduMap.setMyLocationEnabled(true);
        MyLocationData locData = new MyLocationData.Builder()
                .accuracy(bdLocation.getRadius())
                .direction(bdLocation.getDirection())
                .latitude(bdLocation.getLatitude())
                .longitude(bdLocation.getLongitude())
                .build();
        baiduMap.setMyLocationData(locData);
        BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher);

        MyLocationConfiguration config = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.FOLLOWING,true,mCurrentMarker);
        baiduMap.setMyLocationConfigeration(config);
        baiduMap.setMyLocationEnabled(false);
    }

    /**
     * 做一次搜索
     * @param
     */
    private void doSearch(double latitude,double longitude ) {
        PoiNearbySearchOption searchOption = new PoiNearbySearchOption();
        searchOption.location(new LatLng(latitude,longitude))
                .radius(2000)
                .keyword("机床")
                .pageNum(10);
        mPoiSearch.searchNearby(searchOption);
    }


    /**
     * 初始化定位配置信息
     */
    private void initLocation(){
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span=2000;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIgnoreKillProcess(false);//可选，默认false，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        mLocationClient.setLocOption(option);
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent serviceIntent = new Intent(getActivity(), OrderActivity.class);
        startActivity(serviceIntent);
    }

    /**
     * 获取POI检索结果
     * @param result
     */
    @Override
    public void onGetPoiResult(PoiResult result) {
        if (result == null || result.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
            return;
        }
        if (result.error == SearchResult.ERRORNO.NO_ERROR) {
            if(baiduMap != null){
//                baiduMap.clear();
//                //创建PoiOverlay
//                PoiOverlay overlay = new MyPoiOverlay(baiduMap);
//                //设置overlay可以处理标注点击事件
//                baiduMap.setOnMarkerClickListener(overlay);
//                //设置PoiOverlay数据
//                overlay.setData(result);
//                //添加PoiOverlay到地图中
//                overlay.addToMap();
//                overlay.zoomToSpan();
            }
            return;
        }
    }

    /**
     * 获取Place详情页检索结果
     * @param poiDetailResult
     */
    @Override
    public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {

    }

    @Override
    public void onTouch(MotionEvent motionEvent) {
        switch (motionEvent.getAction()){
            case MotionEvent.ACTION_MOVE:
                isMapMove = true;
                break;
            case MotionEvent.ACTION_UP:
                if(isMapMove) {
                    LatLng latLng = baiduMap.getMapStatus().target;
                    System.out.println("----移动了---->" + latLng.latitude + ";" + latLng.longitude);
                    doSearch(latLng.latitude,latLng.longitude);
                }
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.current_city:
                Intent cityIntent = new Intent(getActivity(), ChooseCityActivity.class);
                startActivity(cityIntent);
                break;
        }
    }

//    private class MyPoiOverlay extends PoiOverlay {
//        public MyPoiOverlay(BaiduMap baiduMap) {
//            super(baiduMap);
//        }
//        @Override
//        public boolean onPoiClick(int index) {
//            super.onPoiClick(index);
//            return true;
//        }
//    }
}
